package com.wolfpire.video.controller;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wolfpire.lessonplan.service.LessonPlanService;
import com.wolfpire.profession.service.ProfessionService;
import com.wolfpire.subject.service.SubjectService;
import com.wolfpire.system.common.AuthorityUtils;
import com.wolfpire.system.common.Constants;
import com.wolfpire.system.common.EasyuiPage;
import com.wolfpire.system.common.EasyuiPagination;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.Result;
import com.wolfpire.system.common.springmvc.PrincipalArgument;
import com.wolfpire.system.common.util.StringUtils;
import com.wolfpire.system.model.Attachment;
import com.wolfpire.system.model.Authority;
import com.wolfpire.system.model.DataDict;
import com.wolfpire.system.model.LessonPlan;
import com.wolfpire.system.model.Org;
import com.wolfpire.system.model.Profession;
import com.wolfpire.system.model.Role;
import com.wolfpire.system.model.Subject;
import com.wolfpire.system.model.User;
import com.wolfpire.system.service.AttachmentService;
import com.wolfpire.system.service.RoleService;

/**
 * @author xp
 *
 */

@Controller
@RequestMapping("/video")
public class VideoController {
	@Resource AttachmentService attachmentService;
	
	String Filepath = Constants.FILE_ROOT_PATH;                 //D\:\\CompanyData\\proms
	
	@RequestMapping("/list")
	public ModelAndView list(@PrincipalArgument User user, @RequestParam String filePath) {
		//获取对应菜单的操作权限
//		List<Authority> operAuthorities = getAperAuthorities(user, menuId);
		//List<Authority> operAuthorities = AuthorityUtils.getAperAuthorities(user, menuId);
		System.out.print(filePath);
		ModelAndView mv = new ModelAndView("videoManage/video_list");
		mv.getModelMap().put("filePath", filePath);
		return mv;
	}
	//获取文件的后缀类型
	public String getFileSuffix(String filePath){ 
		int len = filePath.lastIndexOf('.'); 
		return filePath.substring(len+1,filePath.length());
		
	}
	
	@RequestMapping("/listByAttId")
	public ModelAndView list(@PrincipalArgument User user, @RequestParam Long attId) {
		System.out.print(attId);
		String type = null;
		ModelAndView mv = new ModelAndView("videoManage/video_list");
		String filePath = "";
		if(attId != null){
			Attachment attachment = this.attachmentService.get(attId);
			filePath = "\\atta\\" + attachment.getFilePath();
			type = getFileSuffix(filePath);
			//String path = Constants.FILE_ROOT_PATH + "\\" + attachment.getFilePath(); 
			//String imgPath = VideoConverter.processImg(path);
			//String realPath = "\\atta\\" + imgPath.substring(imgPath.indexOf("upload\\"));
			//realPath = realPath.replace("\\", "/");
			//mv.getModelMap().put("realPath", realPath);
			//System.out.println("realPath========" + realPath);
			String imgPath = attachment.getImgPath();
			if(imgPath != null && !"".equals(imgPath))
				mv.getModelMap().put("imgPath", "\\atta\\" + imgPath);
			
			//如果不是MP4和flv的格式  就要进行转码
			if(!"mp4".equals(type)){
				//文件在本地的真实路径
				String path = Constants.FILE_ROOT_PATH + "\\" + attachment.getFilePath(); 
				//取去除文件名后的路径
				String src = path.substring(0, path.lastIndexOf("\\")+1);
				//视频格式转码，返回转码后的文件路径
				String finalPath = VideoConverter.convert(path);
				//取转码后的文件名
				String fileName = finalPath.substring(finalPath.lastIndexOf("\\")+1);
				try {
					//将转码后的文件复制到原本avi文件的路径下（后续应该在复制后将相应的文件删除）
					copyFileUsingFileStreams(finalPath,src + fileName);
					//转码后文件的最终路径
					String str1 = attachment.getFilePath().substring(0, attachment.getFilePath().lastIndexOf("\\")+1);
					//数据库实体路径更改，下次播放就直接转码后的文件
					attachment.setFilePath(str1 + fileName);
					this.attachmentService.update(attachment);
					filePath = "\\atta\\" + attachment.getFilePath();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
				type = "mp4";   //转完后格式为mp4
			}
		}
		mv.getModelMap().put("filePath", filePath);
		mv.getModelMap().put("type", "video/"+ type);
		return mv;
	}
	//文件拷贝
	private void copyFileUsingFileStreams(String sourcePath, String  targetPath)
	        throws IOException {    
		    FileInputStream fis = new FileInputStream(sourcePath);  
	        FileOutputStream fos = new FileOutputStream(targetPath);  
	        int len = 0;  
	        byte[] buf = new byte[1024];  
	        while ((len = fis.read(buf)) != -1) {  
	            fos.write(buf, 0, len);  
	        }  
	        fos.close();  
	        fis.close();  
	}
	
	@RequestMapping("/list1")
	public ModelAndView list1(@PrincipalArgument User user) {
		//获取对应菜单的操作权限
//		List<Authority> operAuthorities = getAperAuthorities(user, menuId);
		//List<Authority> operAuthorities = AuthorityUtils.getAperAuthorities(user, menuId);
		//System.out.print(filePath);
		ModelAndView mv = new ModelAndView("videoManage/video_list1");
		//mv.getModelMap().put("filePath", filePath);
		return mv;
	}
}
